package com.ray.util.weixin;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.ray.pojo.MyUser;
import com.ray.util.WeiXinUtil;

/**
 * WeixinTemplateSender
 * @author Shensg
 * 2018年5月28日
 */
public class WeixinTemplateSender {
	
	/**
	 * 发送模版消息
	 * @param touser
	 * @param templat_id
	 * @param clickurl
	 * @param data
	 * @param accessToken
	 * @return
	 */
	public static String sendWechatmsgToUser(String touser, String templat_id, String clickurl,  JSONObject data,String accessToken){
        String tmpurl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
        String token = accessToken;  //微信凭证，access_token
        String url = tmpurl.replace("ACCESS_TOKEN", token);
        JSONObject json = new JSONObject();
        try {
        	if(null!=clickurl && !"".equals(clickurl) && clickurl.indexOf('?')>0) {
        		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();  
        		if(null!=attributes) {
        			HttpServletRequest request = attributes.getRequest();  
        			MyUser user=(MyUser)request.getSession().getAttribute("userLogin");
        			if(null!=user) {
        				clickurl+="&company="+user.getCompany();
        			}
        		}
        	}
            json.put("touser", touser);
            json.put("template_id", templat_id);
            json.put("url", clickurl);
            json.put("data", data);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String result = httpsRequest(url, "POST", json.toString());
        System.out.println(result);
        try {
            JSONObject resultJson = JSONObject.parseObject(result);
            String errmsg = (String) resultJson.get("errmsg");
            if(!"ok".equals(errmsg)){  //如果为errmsg为ok，则代表发送成功，公众号推送信息给用户了。
                return "error";
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return "success";
    }
	
	
	
	
	
	/**
	 * 请求发送
	 * @param requestUrl 
	 * @param requestMethod
	 * @param outputStr
	 * @return
	 */
	public static String httpsRequest(String requestUrl, String requestMethod, String outputStr){
        try {
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            return buffer.toString();
        } catch (ConnectException ce) {
            System.out.println("连接超时：{}");
        } catch (Exception e) {
            System.out.println("https请求异常：{}");
        }
        return null;
    }
	
	public static String httpRequest(String requestUrl, String requestMethod, String outputStr){
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            return buffer.toString();
        } catch (ConnectException ce) {
            System.out.println("连接超时：{}");
        } catch (Exception e) {
            System.out.println("https请求异常：{}");
        }
        return null;
    }
	/**
	 * test
	 * @param args
	 */
	public static void main(String[] args) {
		String accessToken = "";//WeiXinUtil.getAccessToken();//"10_V3WyI2Is-XUf_EGvSAnOF5CDwGw8cz3TWxDIhTZ2hotgh66Far3Lv6aV74NXwMkRQvCCzyU9Y3WSl0p1dxOfkGMCLjLn39kYsiy6Z8_yi-YF_PR-8mMFJoD0KhcRPpVjvF2MHE81daWkx5DYHHYfABAUUL";//WeiXinUtil.getAccessToken();
		System.out.println("acc:"+accessToken);
		//open id = o_THqw5gxgK4_9qzaFIVFEBQt3Og;//李斌
		JSONObject data=WeixinTemplateList.packJsonToApplyStatus("申请批复通知", "已同意", "李四、王五", "2015.12.03", "你们去现场协助一下", null, null, null, null, null);
		WeixinTemplateSender.sendWechatmsgToUser("o_THqw5gxgK4_9qzaFIVFEBQt3Og", "YZ-XYrfpgePDfNxSxQRrnzPiy35C_ypXi8Iwe3enbiQ", "https://www.baidu.com", data, accessToken);
		
		
		data=WeixinTemplateList.packJsonToAudit("设备&lt;电磁炉&gt;", "你申请对&lt;电磁炉&gt;的控制权限已通过！", "谢福文", "2016/04/29", "立刻体验",null, null, null, null, null);
		WeixinTemplateSender.sendWechatmsgToUser("o_THqw5gxgK4_9qzaFIVFEBQt3Og", "ahq1SEIXCb5mcKe4qQngf8m8kaG5q6ID-VANV0VlGNM", "https://www.baidu.com", data, accessToken);
		
		
		data=WeixinTemplateList.packJsonToCheckWork("我的考勤","张三", "9999", "2015年9月29日 20:21", "早上好！新的一天，新的心情！我们一起努力，根本停不下来！",null, null, null, null, null);
		WeixinTemplateSender.sendWechatmsgToUser("o_THqw5gxgK4_9qzaFIVFEBQt3Og", "X7ZQo8XNaQf_qS63eV1R6oqXeo1GSXBXSU6w0pS9esI", "https://www.baidu.com", data, accessToken);
		
		data=WeixinTemplateList.packJsonToErrorNotice("test测试", "test测试", "test测试", "test测试", "test测试", null, null, null, null, null);
		WeixinTemplateSender.sendWechatmsgToUser("o_THqw5gxgK4_9qzaFIVFEBQt3Og", "SEw74bsrGq2Jz8YDp-QLKz3suxWjjFBQve039-ArmHs", "https://www.baidu.com", data, accessToken);
		
		data=WeixinTemplateList.packJsonToNewOrderNotice("test测试", "test测试", "test测试", "test测试", "test测试","test测试","test测试",null,null, null, null, null, null, null);
		WeixinTemplateSender.sendWechatmsgToUser("o_THqw5gxgK4_9qzaFIVFEBQt3Og", "B_xNvnR6adr9ho_3zNWjqBSuR_R2Ij5FgDVfW6tTbJY", "https://www.baidu.com", data, accessToken);
		
		data=WeixinTemplateList.packJsonToOrderInfoNotice("test测试", "test测试", "test测试", "test测试", "test测试","test测试","test测试",null,null, null, null, null, null, null);
		WeixinTemplateSender.sendWechatmsgToUser("o_THqw5gxgK4_9qzaFIVFEBQt3Og", "W_gzhDzp6mR9az_FipxLL49y-526YdpZVqShVbR93Cc", "https://www.baidu.com", data, accessToken);
		
		data=WeixinTemplateList.packJsonToOrderStatus("test测试", "test测试", "test测试", "test测试", null, null, null, null);
		WeixinTemplateSender.sendWechatmsgToUser("o_THqw5gxgK4_9qzaFIVFEBQt3Og", "8UV_DeCXP5DoVEHuyrDnOjTV7DEta2E_dZHDgg9rr0o", "https://www.baidu.com", data, accessToken);
		
		data=WeixinTemplateList.packJsonToValidCode("test测试", "test测试", "test测试", "test测试", null, null, null, null);
		WeixinTemplateSender.sendWechatmsgToUser("o_THqw5gxgK4_9qzaFIVFEBQt3Og", "9SNq1d6Wed02ZqPqb8tkCvVUIQ7pXq69Fr3nrUcKP0A", "https://www.baidu.com", data, accessToken);
		
		data=WeixinTemplateList.packJsonToWarningNotice("test测试", "test测试", "test测试", "test测试", null, null, null, null);
		WeixinTemplateSender.sendWechatmsgToUser("o_THqw5gxgK4_9qzaFIVFEBQt3Og", "VY94iSA7dZnGzfu7iNdQjzsIFpoOduOLupTNaFDTKj4", "https://www.baidu.com", data, accessToken);
		
		
	}
}
